<template>
<div class="generate">
  <div class="content-box clearfix">
    <e-heading class="title" grade="1" style="margin-top:0">赛程设置</e-heading>
    <el-row class="info-edit">
      <el-col :span="14">
        <div class="grid-content bg-purple">
          <el-form :model="form" :rules="rules" ref="form" label-width="140px">
            <el-form-item label="比赛场地"
               prop="place"
                  :rules="[
                  { required: true, message: '请输入比赛场地'}
                ]">
              <el-input class="normal-input" v-model="form.place" placeholder="请在地图上选取"></el-input>
            </el-form-item>
            <el-form-item label="场地编号"
                prop="placeNumbers"
                  :rules="[
                  { required: true, message: '请输入场地编号'},
                  Object.assign({}, validator.rule.cannotBeEmpty,{message: '请输入场地编号'})
                ]"
             >
              <e-input-group class="field-list" placeholder="请输入场地编号" :max="15" :maxlength="15" v-model="form.placeNumbers" style="width:318px">
              </e-input-group>
            </el-form-item>
            <el-form-item label="每场比赛标准时长（包括中场休息、赛后间隔时间）">
              <el-input-number v-model="form.matchCost">
              </el-input-number>&nbsp;&nbsp;分钟
            </el-form-item>
          </el-form>
        </div>
      </el-col>

      <el-col :span="10">
        <div class="grid-content bg-purple-light map">
          <x-map @locationClick="handleMapClick">
          </x-map>        
        </div>
      </el-col>
    </el-row>   
  </div>
  
  <div class="clearfix cal-container" id="cal-container">
    <div class="select-time">
      <div class="time-pick">
          <el-row>
            <el-col :span="4">
              <label style="line-height:38px;">通用比赛时段：</label>
            </el-col>
            <el-col :span="18" >                
              <e-group :value="timeCommon" class="time-pic" @remove="delTime" @add="addTime">
                <template slot-scope="scope">
                  <el-time-picker        
                      v-if="scope.index==0"             
                      v-model="scope.item.value[0]"
                      :picker-options="{
                        selectableRange: timeCommon[scope.index].value[1] ?
                                        '00:00:00 - ' + new Date(timeCommon[scope.index].value[1]).format('hh:mm:ss'):
                                        '00:00:00 - 23:59:59'
                      }"
                      placeholder="选择开始时间">
                  </el-time-picker>
                  <el-time-picker       
                      v-else              
                      v-model="scope.item.value[0]"      
                      :picker-options="{
                        selectableRange: timeCommon[scope.index].value[1]?
                                        new Date(timeCommon[scope.index-1].value[1]).format('hh:mm:ss') + (' - '+ new Date(timeCommon[scope.index].value[1]).format('hh:mm:ss')):
                                        new Date(timeCommon[scope.index-1].value[1]).format('hh:mm:ss') + ' - 23:59:59'
                      }"               
                      placeholder="选择开始时间">
                  </el-time-picker>

                  <el-time-picker                 
                      v-model="scope.item.value[1]"  
                      :picker-options="{
                        selectableRange: new Date(scope.item.value[0]).format('hh:mm:ss') + ' - 23:59:59'
                      }"                  
                      placeholder="选择结束时间">
                  </el-time-picker>
                </template>
              </e-group>  
            </el-col>
          </el-row>
          </div>                   
      </div>
      <div class="month-select">
        <el-row>
            <el-col :offset="8" :span="5" class="relative">
              <el-date-picker
                v-model="month"
                :picker-options="pickerOptions"
                type="month" 
                placeholder="选择月">
              </el-date-picker>
            </el-col>
            <el-col :offset="3" :span="4" class="relative">
              <i class="line ab green-line"></i><span class="small">通用比赛的时段</span>
            </el-col>
            <el-col :span="4" class="relative">
              <i class="line ab blue-line"></i><span class="small">非通用比赛的时段</span>
            </el-col>
          </el-row>
      </div>
      <!--日历开始-->
      <div class="calendar ">
          <ul class="clearfix week">
            <li class="week-day">
                <el-checkbox v-model="sun"   @change="checkTime($event,0)"></el-checkbox>周日
            </li>
            <li class="week-day">
                <el-checkbox v-model="mon"   @change="checkTime($event,1)"></el-checkbox>周一
            </li>
            <li class="week-day">
                <el-checkbox v-model="tue"   @change="checkTime($event,2)"></el-checkbox>周二
            </li>
            <li class="week-day">
                <el-checkbox v-model="wed"   @change="checkTime($event,3)"></el-checkbox>周三
            </li>
            <li class="week-day">
                <el-checkbox v-model="thu"   @change="checkTime($event,4)"></el-checkbox>周四
            </li>
            <li class="week-day">
                <el-checkbox v-model="fri"   @change="checkTime($event,5)"></el-checkbox>周五
            </li>
            <li class="week-day">
                <el-checkbox v-model="sat"   @change="checkTime($event,6)"></el-checkbox>周六
            </li>
          </ul>
          <div class="dates clearfix">
              <table class="clearfix" >
                  <tr class="day-list clearfix" v-for="(item,index) in trList" :key="index">
                      <td class="day-item relative" v-for="(it,$index) in item" :key="it.date" 
                        v-bind:class="{outDate:it.outOfDate, selected:it.selected, disable: it.disable}"
                        :disabled="it.disabled"
                        @click="handleCheck(it)">
                        {{ new Date(it.date).getDate()}}
                        <div class="ab edit" v-if="it.checked"> <!--比赛日-->
                          <i class="iconfont" @click="openMask($event, it)">&#xe61d;</i>
                          <i class="iconfont" @click="deleteTimes($event,it)">&#xe659;</i>
                        </div>
                        <div class="currency" v-show="it.checked || (!it.common)" @click="showPop($event, it)">
                          <template v-if="it.period.length">
                            <a >{{it.period[0]}}</a>
                          </template>
                          <template v-else>
                            <a v-if="timeCommon[0].value.length">{{timeOne}}-{{timeTwo}}</a>
                          </template>                          
                        </div>
                      </td>                      
                  </tr>
              </table>
          </div>
      </div>           

    <div class="mask" v-show="maskVisible">
      <div class="message-box">
        <div class="message-box-head">
          <div class="message-box-title">可比赛时段</div>
          <i class="el-icon-close ab close" @click="closeMask()"></i>
        </div>
        <div class="message-box-body">
          <div v-for="(item,index) in specialTimeList" :key="index" class="time-pic">
            <el-time-picker  v-if="index==0"
                v-model="item.value[0]"
                :picker-options="{
                  selectableRange: specialTimeList[index].value[1] ?
                                  '00:00:00 - ' + new Date(specialTimeList[index].value[1]).format('hh:mm:ss'):
                                  '00:00:00 - 23:59:59'
                }"
                placeholder="选择时间范围">
            </el-time-picker>

            <el-time-picker  v-else
                v-model="item.value[0]"
                :picker-options="{
                  selectableRange:specialTimeList[index].value[1]? 
                                  new Date(specialTimeList[index-1].value[1]).format('hh:mm:ss') + (' - '+ new Date(specialTimeList[index].value[1]).format('hh:mm:ss')):
                                  new Date(specialTimeList[index-1].value[1]).format('hh:mm:ss') + ' - 23:59:59'
                }" 
                placeholder="选择时间范围">
            </el-time-picker>

            <el-time-picker  
                v-model="item.value[1]"          
                :picker-options="{
                  selectableRange: new Date(item.value[0]).format('hh:mm:ss') + ' - 23:59:59'
                }"      
                placeholder="选择时间范围">
            </el-time-picker>
            <el-button class="btn-icon" icon="minus" @click="delSpecialTime(index)"></el-button>
          </div>     
          <el-button class="add-time btn-icon" style="margin-left:172px" icon="plus" @click="addSpecialTime()" 
            :disabled="specialTimeList.length>=6">添加时段</el-button>
        </div>
        <div class="message-box-foot">
            <el-button type="primary" @click="sureMask()">确定</el-button>
            <el-button @click="cancelMask()">取消</el-button>
        </div>
      </div>
    </div>
    <!--弹出气泡框-->
    <div class="ab" v-bind:style="{left: point.x +'px',top: point.y +'px'}" v-show="popVisible">
      <div class="popover right" >
        <i class="el-icon-close icon-close" @click="popVisible=false"></i>       
        <div class="title">比赛的时段</div>    
        <div class="time-item" >
          <div v-if="popIsSpecial">
            <el-row class="time" v-for="(item,$index) in popTimes" :key="$index" v-if="item">
              <el-col :offset="5" :span="2"><span class="tag">{{$index+1}}</span></el-col>
              <el-col :span="12">{{ item}}</el-col>
            </el-row>
          </div>      
          <div v-else>
            <el-row class="time" v-for="(item,$index) in popTimes" :key="$index" v-if="item.value.length">
              <el-col :offset="5" :span="2"><span class="tag">{{$index+1}}</span></el-col>
              <el-col :span="4">{{ new Date(item.value[0]).format('hh:mm')}}</el-col>
              <el-col :span="4">——</el-col>
              <el-col :span="4">{{ new Date(item.value[1]).format('hh:mm') }}</el-col>
            </el-row>
          </div>          
        </div>        
        <div class="arrow"></div>
      </div>
    </div>      
  </div>

  <div class="btn-gp">
    <el-button @click="buildPreview()">赛程预览</el-button>    
    <el-button type="primary" @click="buildDirect()">生成赛程</el-button>
  </div>
</div>
  
</template>

<script>
import Api from 'api/race'
import EInputGroup from '@e-ui/InputGroup'
import EGroup from '@e-ui/Group'
import {mapGetters} from 'vuex'
import validator from 'utils/validator'
import {cloneObj, dateToTimestamp, minuteDiff, formatDate, addDate, IsCupSeperate} from 'utils'
import XMap from './components/XMap'

export default {
  components: {
    EInputGroup, EGroup, XMap
  },
  computed: {
    ...mapGetters({
      race_detail: 'race_detail',
      schedule: 'race_schedule',
      has_schedule: 'race_has_schedule',
      time_common: 'race_time_common'
    }),
    IsCupSeperate () { // 是杯赛分离模式
      return IsCupSeperate(this.race_detail)
    },
    isLeague () { // 是积分联赛双循环
      return this.race_detail.matchFormatStr.includes('积分')
    },
    isKnockout () { // 淘汰赛
      return ['淘汰制1场', '淘汰赛1场'].indexOf(this.race_detail.matchFormatStr) > -1
    },
    isCup () { // 杯赛
      return this.race_detail.matchFormatStr.includes('杯赛')
    },
    timeOne () {
      return new Date(this.timeCommon[0].value[0]).format('hh:mm')
    },
    timeTwo () {
      return new Date(this.timeCommon[0].value[1]).format('hh:mm')
    },
    startDate () {
      return new Date(this.race.startTime).format('yyyy-MM-dd')
    },
    endDate () {
      return new Date(this.race.endTime).format('yyyy-MM-dd')
    },
    sun () {
      return this.trList.every(item => {
        return item[0].checked
      })
    },
    mon () {
      return this.trList.every(item => {
        return item[1].checked
      })
    },
    tue () {
      return this.trList.every(item => {
        return item[2].checked
      })
    },
    wed () {
      return this.trList.every(item => {
        return item[3].checked
      })
    },
    thu () {
      return this.trList.every(item => {
        return item[4].checked
      })
    },
    fri () {
      return this.trList.every(item => {
        return item[5].checked
      })
    },
    sat () {
      return this.trList.every(item => {
        return item[6].checked
      })
    },
    scheduleMatchId () {
      return this.schedule && this.schedule.matchId
    }
  },
  created () {
    if (this.has_schedule && parseInt(this.scheduleMatchId) === parseInt(this.$route.query.id)) {
      this.setScheduleInfo()
    }
  },
  mounted () {
    this.getRaceDetail()
    this.getMatchCount()
  },
  destroyed () {
  },
  watch: {
    month (newVal, oldVal) {
      this.getRaceDate(new Date(oldVal).format('yyyy-MM'), new Date(newVal).format('yyyy-MM'))
    }
  },
  data () {
    let self = this
    return {
      errorCount: 0,
      popTimes: [], // 气泡框上展示的时间段
      popIsSpecial: false,
      race: {},
      map: {},
      fieldList: [],
      matchTotal: 0,
      validator,
      rules: {},
      monthList: {}, // 已选择的月份
      commonTime: 0, // 通用比赛日时间总和
      selectedDates: [], // 选中的日期
      form: {
        matchId: Number(this.$route.query.id),
        place: '',
        placeNumbers: [],
        matchCost: 90,
        longitude: 121.59996,
        latitude: 31.197646,
        periodData: [
          {
            date: '2017-07-27',
            period: [
              '10:00-12:00'
            ],
            common: true
          }
        ]
      },
      markers: [],
      center: [121.59996, 31.197646],
      lng: 0,
      lat: 0,
      loaded: false,
      pickerOptions: {
        disabledDate (time) {
          var start = new Date(self.race.startTime)
          var y = start.getFullYear().toString()
          var M = start.getMonth() + 1 > 10 ? (start.getMonth() + 1).toString() : '0' + (start.getMonth() + 1).toString()
          var sDate = y + '-' + M + '-01'
          return time.getTime() < new Date(sDate) - 8.64e7
        }
      },
      month: new Date(), // 选择的月份
      maskVisible: false,
      popVisible: false,
      specialTimeList: [
        {value: []}
      ],
      point: {
        x: 100,
        y: 100
      },
      trList: [],
      timeCommon: [
        {value: []}
      ], // 通用比赛时间段
      specialOne: {},
      timeCountMax: 7 // 比赛时段最大个数
    }
  },
  methods: {
    // 设置已有的赛程信息
    setScheduleInfo () {
      let f = this.form
      let s = this.schedule
      f.place = s.place
      f.placeNumbers = s.placeNumbers
      f.matchCost = s.matchCost
      f.latitude = s.latitude
      f.longitude = s.longitude
      this.timeCommon = this.time_common
    },
    // 设置已选日期信息
    setSelectedDay () {
      if (this.has_schedule && parseInt(this.scheduleMatchId) === parseInt(this.$route.query.id)) {
        this.trList.forEach(yue => {
          yue.forEach(day => {
            this.schedule.periodData.forEach(item => {
              if (day.date === item.date) {
                day.common = item.common
                day.checked = true
                if (!item.common) { // 特殊比赛日
                  day.period = item.period
                }
              }
            })
          })
        })
      }
    },
    // 获取赛事信息
    getRaceDetail () {
      Api.detail({matchId: this.$route.query.id}).then((res) => {
        this.race = res.data
        this.race.startTime = new Date(this.race.startTime).format()
        this.race.endTime = new Date(this.race.endTime).format()
        this.month = new Date(this.race.startTime).format('yyyy-MM')
        this.getRaceDate()
      })
    },
    // 根据月份获取日期
    getRaceDate (old, newMonth) {
      if (this.trList.length) {
        let o = old.replace('-', '')
        if (Number.isInteger(parseInt(o))) {
          this.monthList[o] = cloneObj(this.trList)
        }
      }
      let m = newMonth && newMonth.replace('-', '')
      if (isNaN(parseInt(m))) {
        return
      }
      if (this.monthList[m]) { // 已有月份信息
        this.trList = this.monthList[m]
        this.setSelectedDay()
        return
      }
      Api.getRaceDate({ // 无月份信息
        year: new Date(this.month).getFullYear(),
        month: new Date(this.month).getMonth() + 1
      }).then((res) => {
        this.trList = res.data.map((item, index) => {
          return item.map(it => {
            return {
              date: it,
              checked: false,
              period: [],
              common: true,
              outOfDate: formatDate(it) > formatDate(this.race.endTime) + 8.64e7 || formatDate(it) < formatDate(this.race.startTime),
              disable: new Date(it).getMonth() !== new Date(this.month).getMonth()
            }
          })
        })
        this.setSelectedDay()
      })
    },
    // 获取比赛总场次
    getMatchCount () {
      Api.getMatchCount({
        matchId: this.$route.query.id
      }).then((res) => {
        this.matchTotal = res.data.totalPlayCount
      })
    },
    // 设置特殊比赛日
    sureMask () {
      this.specialOne.selected = true
      this.specialOne.common = false
      this.specialOne.period = []
      for (var i = 0, l = this.specialTimeList.length; i < l; i++) {
        if ((this.specialTimeList[i].value[0] !== undefined) && this.specialTimeList[i].value[1] !== undefined) {
          this.specialOne.period.push(this.specialTimeList[i].value[0].format('hh:mm') + '-' + this.specialTimeList[i].value[1].format('hh:mm'))
        }
      }
      this.specialOne = {}
      this.specialTimeList = []
      this.closeMask()
    },
    cancelMask () {
      this.specialTimeList.length = 0
      this.closeMask()
    },
    closeMask () {
      this.maskVisible = false
    },
    openMask (ev, item) {
      ev.stopPropagation()
      if (item.checked) {
        this.popVisible = false
        this.specialOne = item
        this.specialTimeList = []
        var y = new Date().getFullYear()
        var m = new Date().getMonth() + 1
        var d = new Date().getDate()
        for (var i = 0, l = item.period.length; i < l; i++) {
          this.specialTimeList.push({
            value: [
              new Date(y, m, d, item.period[i].substr(0, 2), item.period[i].substr(3, 2)),
              new Date(y, m, d, item.period[i].substr(6, 2), item.period[i].substr(9, 2))
            ]
          })
        }
        this.maskVisible = true
      }
    },
    // 判断是否选择了通用比赛时段
    handleCheckCommonTime () {
      if (this.timeCommon[0].value[0] == undefined || this.timeCommon[0].value[1] == undefined) { //eslint-disable-line
        this.$message({
          message: '请先设置一个通用时段',
          type: 'warning'
        })
        return false
      }
      return true
    },
    checkTime (e, index) {
      var commonChecked = this.handleCheckCommonTime()
      if (!commonChecked) {
        return
      }
      e.currentTarget.cancelable = true
      e.currentTarget.defaultPrevented = true
      e.stopPropagation()
      this.handleCheckGroup(e, index)
    },
    // 选中周几下面的每一天为通用比赛日
    handleCheckGroup (e, col) {
      var canCheckDay = this.trList.filter(item => { // 可选的日期长度
        return !item[col].disable && !item[col].outOfDate
      })
      var checked = this.trList.filter(item => { // 已选的日期长度
        return item[col].checked
      })
      if (checked.length === canCheckDay.length) {
        this.trList.forEach(row => {
          if (dateToTimestamp(row[col].date) >= dateToTimestamp(this.race.startTime) &&
            dateToTimestamp(this.race.endTime) + 8.64e7 > dateToTimestamp(row[col].date) &&
            (!row[col].disable)) {
            row[col].checked = false
          }
        })
      } else {
        this.trList.forEach(row => {
          if (dateToTimestamp(row[col].date) >= dateToTimestamp(this.race.startTime) &&
            dateToTimestamp(this.race.endTime) + 8.64e7 > dateToTimestamp(row[col].date) &&
            (!row[col].disable)) {
            row[col].checked = true
          }
        })
      }
    },
    // 选中某一天为通用比赛日
    handleCheck (item) {
      var commonChecked = this.handleCheckCommonTime()
      if (!commonChecked) {
        return
      }
      if (dateToTimestamp(item.date) >= dateToTimestamp(this.startDate) &&
      dateToTimestamp(this.endDate) + 8.64e7 > dateToTimestamp(item.date) && (!item.disable)) {
        item.checked = !item.checked
      }
    },
    // 添加通用时段
    addTime () {
      var l = this.timeCommon.length - 1
      if (this.timeCommon[l].value[0] == undefined || this.timeCommon[l].value[1] == undefined) { // eslint-disable-line
        this.$message({
          message: '请输入完整的比赛时段',
          type: 'warning'
        })
        return
      }
      if (this.timeCommon.length < this.timeCountMax) {
        this.timeCommon.push({value: []})
      }
    },
    // 删除一个通用时段
    delTime (index) {
      this.timeCommon.splice(index, 1)
    },
    // 添加特殊时段
    addSpecialTime () {
      var l = this.specialTimeList.length
      if (l > 0 && (this.specialTimeList[l - 1].value[0] == undefined || this.specialTimeList[l - 1].value[1] == undefined)) { // eslint-disable-line
        this.$message({
          message: '请输入完整的比赛时段',
          type: 'warning'
        })
        return
      }
      if (this.specialTimeList.length < this.timeCountMax) {
        this.specialTimeList.push({value: []})
      }
    },
    // 删除一个特殊时段
    delSpecialTime (i) {
      this.specialTimeList.splice(i, 1)
    },
    // 删除当天所有特殊比赛时段
    deleteTimes (event, item) {
      if (item.common) {
        return false
      }
      this.specialOne = item
      event.stopPropagation()
      this.$confirm('确定要将该日期删除吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        item.period = []
        item.selected = false
        item.common = true
      })
    },
    showPop (ev, item) {
      this.popVisible = true
      ev.stopPropagation()
      this.point.x = ev.pageX + 11 || ev.clientX // - ev.offsetX
      this.point.y = ev.pageY - 24 || ev.clientY // - ev.offsetY
      if (!item.common) {
        this.popTimes = item.period
        this.popIsSpecial = true
      } else {
        this.popTimes = this.timeCommon
        this.popIsSpecial = false
      }
    },
    // 生成赛程预览
    buildPreview () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let isValid = this.customValid()
          if (!isValid.isSuccess) {
            this.$message({
              message: isValid.msg,
              type: 'warning'
            })
          } else {
            this.formatData()
            var form = cloneObj(this.form)
            Api.buildSchedulePrev(form, {context: this}).then((res) => {
              this.$store.commit('RACE_SCHEDULE', {
                form: form,
                timeCommon: this.timeCommon
              })
              let toUrl = this.isCup ? '/race/detail/manage/schedulepre' : '/race/detail/manage/preview'
              this.$router.push({path: toUrl,
                query: {
                  id: this.$route.query.id,
                  tasktype: this.$route.query.tasktype,
                  isRun: this.$route.query.isRun
                }
              })
            }).catch((err) => {
              this.$message({
                message: err.msg,
                type: 'warning'
              })
            })
          }
        } else {
          return false
        }
      })
    },
    // 直接生成赛程
    buildDirect () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let isValid = this.customValid()
          if (!isValid.isSuccess) {
            this.$message({
              message: isValid.msg,
              type: 'warning'
            })
          } else {
            this.formatData()
            var form = cloneObj(this.form)
            Api.buildScheduleDirect(form, {context: this}).then((res) => {
              this.$store.commit('RACE_HAS_SCHEDULE', false)
              this.$store.commit('RACE_SCHEDULE', {})
              let nextPath = ''
              if (this.isKnockout) { // 单淘汰赛
                nextPath = '/race/detail/manage/schedulecheck'
              } else if (this.isCup) { // 杯赛
                nextPath = '/race/detail/manage/schedulecup'
              } else { // 双循环
                nextPath = '/race/detail/manage/edit'
              }
              this.$router.push({
                path: nextPath,
                query: this.$route.query
              })
            }).catch((err) => {
              this.$message({
                message: err.msg,
                type: 'warning'
              })
            })
          }
        } else {
          return false
        }
      })
    },
    // 判断生成的时间段是否符合规则
    customValid () {
      for (var i = 0, l = this.timeCommon.length; i < l; i++) {
        if (!this.timeCommon[i].value[0] || !this.timeCommon[i].value[1]) {
          return {
            msg: '请设置开始时间和结束时间',
            isSuccess: false
          }
        }
        var timeDiff = minuteDiff(this.timeCommon[i].value[1], this.timeCommon[i].value[0])
        if (timeDiff < this.form.matchCost) {
          return {
            msg: '通用比赛时段间隔时间不能少于您设置的每场比赛标准时长',
            isSuccess: false
          }
        }
      }
      var currentMon = new Date(this.month).format('yyyyMM')
      if (!this.monthList[currentMon]) {
        this.monthList[currentMon] = this.trList
      }
      let commonGamePerDay = 0
      this.timeCommon.forEach(item => {
        var min = minuteDiff(item.value[1], item.value[0])
        commonGamePerDay += Math.floor(min / this.form.matchCost)
      })
      var commonDays = []
      let specialGames = 0
      var d = new Date()
      var y = d.getFullYear()
      var mon = d.getMonth() + 1
      var dat = d.getDate()
      for (var it in this.monthList) {
        if (Array.isArray(this.monthList[it])) {
          var month = this.monthList[it]
          for (var m = 0, len = month.length; m < len; m++) {
            for (var n = 0, nlen = month[n].length; n < nlen; n++) {
              if (month[m][n].checked && month[m][n].common && (commonDays.indexOf(month[m][n].date) === -1)) { // 通用比赛日
                commonDays.push(month[m][n].date)
              }
              if (!month[m][n].common) { // 特殊比赛日
                var day = month[m][n]
                for (var x = 0, xlen = day.period.length; x < xlen; x++) {
                  var time1 = new Date(y, mon, dat, Number(day.period[x].substr(0, 2)), Number(day.period[x].substr(3, 2)))
                  var time2 = new Date(y, mon, dat, Number(day.period[x].substr(6, 2)), Number(day.period[x].substr(9, 2)))
                  var minutes = minuteDiff(time2, time1)
                  if (minutes < this.form.matchCost) {
                    return {
                      msg: '特殊比赛日:' + day.date + '比赛时间间隔时间不能少于您设置的每场比赛标准时长',
                      isSuccess: false
                    }
                  } else {
                    specialGames += Math.floor(minutes / this.form.matchCost)
                  }
                }
              }
            }
          }
        }
      }
      var commonGameTotal = commonGamePerDay * commonDays.length * this.form.placeNumbers.length
      var specialGameTotal = specialGames * this.form.placeNumbers.length
      var gameTotal = commonGameTotal + specialGameTotal // 计算出的总比赛场数
      if (gameTotal >= this.matchTotal) {
        return {
          isSuccess: true
        }
      } else {
        this.errorCount++
        if (this.errorCount >= 3) {
          this.race.endTime = addDate(this.race.endTime, 10000)
          this.trList.forEach(w => {
            w.forEach(d => {
              d.outOfDate = formatDate(d.date) > formatDate(this.race.endTime) + 8.64e7 || formatDate(d.date) < formatDate(this.race.startTime)
            })
          })
          return {
            msg: '当前选择的可用比赛日期不够，已经自动为您增加了可选择的比赛日期！',
            isSuccess: false
          }
        }
        return {
          msg: '您设置的比赛时长不足以生成足够的赛程',
          isSuccess: false
        }
      }
    },
    // 生成提交数据
    formatData () {
      this.form.periodData = []
      var pdList = []
      for (var month in this.monthList) {
        if (Array.isArray(this.monthList[month])) {
          var yue = this.monthList[month]
          yue.forEach(week => {
            week.forEach(day => {
              if (day.checked && day.common && pdList.indexOf(day) === -1) { // 选中的通用比赛日
                day.period = []
                for (var i = 0, len = this.timeCommon.length; i < len; i++) {
                  day.period.push(new Date(this.timeCommon[i].value[0]).format('hh:mm') + '-' + new Date(this.timeCommon[i].value[1]).format('hh:mm'))
                }
                pdList.push(day)
              }
              if (!day.common && pdList.indexOf(day) === -1) { // 特殊比赛日
                pdList.push(day)
              }
            })
          })
        }
      }
      this.form.periodData = pdList
    },
    handleMapClick (p) {
      this.form.latitude = p.lat
      this.form.longitude = p.lng
      this.form.place = p.formattedAddress
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/calendar.scss';   
.generate{
  padding-bottom:100px;
}
.el-vue-search-box-container{
  width:358px;
}
.title{
  margin-bottom: 20px;
}
.normal-input{
  width: 318px;
}
.map{
  width: 358px;
  height: 216px;
}
.amap-geolocation-con{
  z-index: 1999!important;
}
.info-edit{
  height: 250px;
}
.btn-gp{
  text-align:center;
  margin-top: 40px;
}
.time-picker{
  margin-bottom:10px;
  margin-left:90px;
}
.time-pic{
  margin-bottom:10px;
}
</style>
<style>
.field-list .input-middle{
  width:280px!important;
}
</style>
